import { api } from "@/api";
import { useAppStore } from "@/stores/app";
import { TUICallType, TUICallKitServer } from "@tencentcloud/call-uikit-vue2";

/** @type {MediaRecorder} */
let mediaRecorder;
const chunks = [];
let micOK = false

export async function initMic() {
  await createMicRecorder()
  stopTracks()
  mediaRecorder?.stop()
  mediaRecorder = null
}

function stopTracks() {
  mediaRecorder && mediaRecorder.stream.getTracks().forEach(track => track.stop())
}

export async function createMicRecorder() {
  return navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
    mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.ondataavailable = function (event) {
      chunks.push(event.data);
    };
    micOK = true
  }).catch(function (err) {
    micOK = false
    mediaRecorder = null
    console.log('无法访问麦克风:', err);
  });
}

export async function startRecord() {
  if (mediaRecorder || mediaRecorder?.state === 'recording') return
  chunks.length = 0
  await createMicRecorder()
  mediaRecorder.start();
}

export async function stopRecord() {
  return new Promise(resolve => {
    stopTracks()
    mediaRecorder.stop()
    mediaRecorder.onstop = function () {
      resolve(chunks.splice(0, chunks.length))
    };
    mediaRecorder = null
  })
}

export function isMicOK() {
  return micOK
}

export async function initCall() {
  const appStore = useAppStore()
  try {
    const { UserSig } = await api.getUserSig({ userName: appStore.accessToken })
    await TUICallKitServer.init({
      SDKAppID: Number(process.env.VUE_APP_SDKAPPID),
      userID: appStore.accessToken,
      userSig: UserSig,
    });
    console.log("[TUICallKit] Initialization succeeds.");
  } catch (error) {
    console.log(`[TUICallKit] Initialization failed. Reason: ${error}`);
  }
}

export async function call(username, isVoice = true, groupID) {
  try {
    const type = isVoice ? TUICallType.AUDIO_CALL : TUICallType.VIDEO_CALL
    if (groupID) {
      await TUICallKitServer.groupCall({
        type,
        groupID,
        userIDList: username
      })
    } else {
      // 1v1 video call
      await TUICallKitServer.call({
        userID: username,
        type: isVoice ? TUICallType.AUDIO_CALL : TUICallType.VIDEO_CALL,
      });
    }
  } catch (error) {
    console.log(`[TUICallKit] Call failed. Reason: ${error}`);
  }
}
